#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/16  0:10
# @Author: 余浪人
# @email: yulangren520@gmail.com

from apps import get_sys_uri
from apps.lib.public import get_date_str, get_uuid_16, get_hash
from apps.models.collector_model import Collect_History_Model
from apps.models.document_model import Document_modle, db
from flask import jsonify
import requests, os
from apps.setting import Config


def publish_data(data: dict):
    '''
    发布内容制数据
    :param data:
    :return:
    '''
    try:
        title = data.get('title')
        ha_str = get_hash(title)  # 得到哈希值
        coll_cout = Collect_History_Model.query.filter(Collect_History_Model.identifying_code == ha_str).count()
        if not coll_cout:  # 历史不存在时
            obj = Document_modle()  # 档案
            obj_history = Collect_History_Model()  # 历史记录
            obj.set_attrs(data)
            obj_history.set_attrs(data)
            obj_history.set_attrs({"identifying_code": ha_str})
            db.session.add(obj)  # 写入文档数据库
            db.session.add(obj_history)  # 写入历史
            db.session.commit()  # 提交数据
    except:
        pass


def save_img(url: str, path='images/'):
    '''
    图片文件本地化
    :param url:
    :param path:
    :return:
    '''
    error = None
    base_path = os.path.join(get_sys_uri(), 'apps')
    relative_path = os.path.join('/static/', Config.FILE_PATH, path, get_date_str(),
                                 get_uuid_16() + '.' + url.split('.')[-1])
    abs_path = base_path + relative_path
    dirname = os.path.dirname(abs_path)
    if not os.path.exists(dirname):
        try:
            os.makedirs(dirname)
        except:
            error = '创建目录失败!'
    elif not os.access(dirname, os.W_OK):
        error = '没有写入权限!'
    if not error:
        try:
            response = requests.get(url).content
            with open(base_path + relative_path, 'wb') as fp:
                fp.write(response)
            return relative_path
        except:
            pass


if __name__ == '__main__':
    data = save_img('http://www.xuks.top/public/cover/55/bb/6f/55bb6f8591f56278b014902e8e0c0f6c.jpg')
    print(data)
